<script lang="ts" setup>
import type { FormInstance, DrawerProps } from 'ant-design-vue';
import { $t } from '@vben/locales';
import type { MinishopSpu } from './types';
import { onMounted, reactive, ref, watch, computed, toRefs } from 'vue';
import { message } from 'ant-design-vue';
import { removeEmpty, removeNull } from '#/utils/common';
import ImageUpload from '#/components/ImageUpload.vue';
import { useDebounceFn } from '@vueuse/core';
import dayjs, { Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import type { ComponentSetting } from '../../uctoo/component_setting/types.ts';
import { uctoo_minishop_spu, uctoo_component_setting } from '#/store';
import { useRepo } from 'pinia-orm';
import { useAxiosRepo } from '@pinia-orm/axios';
import { VbenIcon } from '@vben-core/shadcn-ui';

// 加载 utc 和 timezone 插件
dayjs.extend(utc);
dayjs.extend(timezone);
const loading = ref(false);

const props = defineProps<{
  mode: 'add' | 'edit';
  record: MinishopSpu | null;
  visible: boolean;
  componentSettingData: ComponentSetting[];
  ids?:(string[] | number[]);
}>();

// 计算属性判断空值
const isIdsEmpty = computed(() => 
  !props.ids || props.ids.length === 0
);

const emit = defineEmits(['update:visible', 'success']);

const ENTITY_PROXY: { [K in keyof MinishopSpu]: null } = {
id: null,
out_product_id: null,
title: null,
subtitle: null,
headimg: null,
status: null,
edit_status: null,
min_price: null,
cats: null,
attrs: null,
model: null,
dispatch_type: null,
express_info: null,
shopcat: null,
skus: null,
sales_count: null,
weigh: null,
template_id: null,
ext_json: null,
memo: null,
ext_attrs: null,
creator: null,
start_at: null,
end_at: null,
meet_at: null,
address: null,
latitude: null,
longitude: null,
created_at: null,
updated_at: null,
deleted_at: null,
desc_info: null,
brand_id: null,
};
 
// 获取有效字段选项
const getFieldOptions = () => {
  // 排除系统字段
  const EXCLUDED_FIELDS = ['id', 'creator', 'created_at', 'updated_at', 'deleted_at'] as const;
  
  return (Object.keys(ENTITY_PROXY) as Array<keyof MinishopSpu>).filter(
    field => !EXCLUDED_FIELDS.includes(field as typeof EXCLUDED_FIELDS[number])
  );
};
const formRef = ref<FormInstance>();


const formState = reactive<Record<keyof MinishopSpu, any>>(
  Object.fromEntries(
    getFieldOptions().map(k => [k, '']) // 初始化所有有效字段
  ) as Record<keyof MinishopSpu, any>
);
     // 用户选择的表单项，初始化为表单所有项或根据需求预选一些项
    const selectedFormItems = ref<Array<keyof MinishopSpu>>(Object.keys(formState) as Array<keyof MinishopSpu>);
    const handleFormItemChange = () => {
      console.log('Selected columns:', selectedFormItems.value);
    }; 

/** rules */
const rules = {
 out_product_id: [{message: $t('page.Required'), required: false}],
 title: [{message: $t('page.Required'), required: true}],
 subtitle: [{message: $t('page.Required'), required: false}],
 headimg: [{message: $t('page.Required'), required: true}],
 status: [{message: $t('page.Required'), required: true}],
 edit_status: [{message: $t('page.Required'), required: true}],
 min_price: [{message: $t('page.Required'), required: true}],
 cats: [{message: $t('page.Required'), required: false}],
 attrs: [{message: $t('page.Required'), required: false}],
 model: [{message: $t('page.Required'), required: false}],
 dispatch_type: [{message: $t('page.Required'), required: false}],
 express_info: [{message: $t('page.Required'), required: false}],
 shopcat: [{message: $t('page.Required'), required: false}],
 skus: [{message: $t('page.Required'), required: false}],
 sales_count: [{message: $t('page.Required'), required: true}],
 weigh: [{message: $t('page.Required'), required: true}],
 template_id: [{message: $t('page.Required'), required: false}],
 ext_json: [{message: $t('page.Required'), required: false}],
 memo: [{message: $t('page.Required'), required: false}],
 ext_attrs: [{message: $t('page.Required'), required: false}],
 start_at: [{message: $t('page.Required'), required: false}],
 end_at: [{message: $t('page.Required'), required: false}],
 meet_at: [{message: $t('page.Required'), required: false}],
 address: [{message: $t('page.Required'), required: false}],
 latitude: [{message: $t('page.Required'), required: false}],
 longitude: [{message: $t('page.Required'), required: false}],
 desc_info: [{message: $t('page.Required'), required: false}],
 brand_id: [{message: $t('page.Required'), required: false}],
};


watch(
  () => props.record,
  (newVal) => {
    if (newVal) {
      Object.assign(formState, newVal);
    } else {
      Object.keys(formState).forEach((key) => {
        formState[key as keyof MinishopSpu] = '';
      });
    }

    if(props.componentSettingData[0]){
      selectedFormItems.value = JSON.parse(props.componentSettingData[0].selected_form_column ?? '[]');
    }
  },
  { immediate: true },
);

const handleOk = () => {
  if(isIdsEmpty.value){ //单条数据编辑提交
  console.log(formState);
    interface Formated {
      id?:string,
      out_product_id?: string,
      title?: string,
      subtitle?: string,
      headimg?: string,
      status?: number,
      edit_status?: number,
      min_price?: number,
      cats?: string,
      attrs?: string,
      model?: string,
      dispatch_type?: string,
      express_info?: string,
      shopcat?: string,
      skus?: string,
      sales_count?: number,
      weigh?: number,
      template_id?: string,
      ext_json?: string,
      memo?: string,
      ext_attrs?: string,
      start_at?: Date,
      end_at?: Date,
      meet_at?: Date,
      address?: string,
      latitude?: number,
      longitude?: number,
      desc_info?: string,
      brand_id?: number,
     };

    const formatedFormState: Formated = {
      id: formState.id,
      out_product_id: formState.out_product_id,
      title: formState.title,
      subtitle: formState.subtitle,
      headimg: formState.headimg,
      status: Number(formState.status),
      edit_status: Number(formState.edit_status),
      min_price: Number(formState.min_price),
      cats: formState.cats,
      attrs: formState.attrs,
      model: formState.model,
      dispatch_type: formState.dispatch_type,
      express_info: formState.express_info,
      shopcat: formState.shopcat,
      skus: formState.skus,
      sales_count: Number(formState.sales_count),
      weigh: Number(formState.weigh),
      template_id: formState.template_id,
      ext_json: formState.ext_json,
      memo: formState.memo,
      ext_attrs: formState.ext_attrs,
      start_at: formState.start_at,
      end_at: formState.end_at,
      meet_at: formState.meet_at,
      address: formState.address,
      latitude: Number(formState.latitude),
      longitude: Number(formState.longitude),
      desc_info: formState.desc_info,
      brand_id: Number(formState.brand_id),
     };

  formRef.value?.validate().then(async () => {
    try {
      if (props.mode === 'add') {
        delete formatedFormState['id'];
        await useAxiosRepo(uctoo_minishop_spu).api().adductooMinishopSpu(removeEmpty(formatedFormState));
        message.success($t('page.AddSuccess'));
      } else {
        await useAxiosRepo(uctoo_minishop_spu).api().edituctooMinishopSpu(removeNull(formatedFormState));
          message.success($t('page.EditSuccess'));        
      }
      emit('success');
    } catch {
      message.error($t('page.EditFailed'));
    }
  });
  }else{ //多条数据编辑提交
    handleSubmit();
  }
  
};

const placement = ref<DrawerProps['placement']>('left');
const open = ref<boolean>(false);
const handleCancel = () => {
  emit('update:visible', false);
};

const showDrawer = () => {
  open.value = true;
};

const onClose = () => {
  open.value = false;
};

const onSetting = async () => {
  try {
      if(props.componentSettingData[0]){
        props.componentSettingData[0].selected_form_column = JSON.stringify(selectedFormItems.value);
      }
      await useAxiosRepo(uctoo_component_setting).api().edituctooComponentSetting(removeEmpty(props.componentSettingData[0]));
        message.success($t('page.SaveSuccess'));
    } catch {
      message.error($t('page.EditFailed'));
    }
  open.value = false;
};

// 动态表单项
interface FormField {
  selectedField?: keyof MinishopSpu;
  inputValue: string | number;
}

// 响应式表单数据
const formFields = reactive<FormField[]>(
  Array.from({ length: 1 }, () => ({
    selectedField: undefined,
    inputValue: ''
  }))
);

// 添加表单项
const addField = () => {
  formFields.push({ selectedField: undefined, inputValue: '' });
};

const removeField = (index: number) => {
  if (formFields.length > 1) {
    formFields.splice(index, 1);
  }
};

// 处理字段选择变化
const handleFieldChange = (index: number, value: keyof MinishopSpu) => {
  // 检查是否已存在相同字段
  const isDuplicate = formFields.some(
    (f, i) => i !== index && f.selectedField === value
  );  
  if (isDuplicate) {
    message.error($t('page.DuplicateSeletedField'));
    return;
  }

  const currentField = formFields[index];
  if (!currentField) return;
  // 清除旧字段的关联状态
  if (currentField.selectedField) {
    delete formState[currentField.selectedField];
  }
  // 更新字段并初始化值
  currentField.selectedField = value;
  currentField.inputValue = isNumberField(value) ? 0 : '';
  // 更新表单状态
  formState[value] = currentField.inputValue;
};

const isNumberField = (field: keyof MinishopSpu): boolean => {
  const NUMBER_FIELDS: (keyof MinishopSpu)[] = ['status','edit_status','min_price','sales_count','weigh','latitude','longitude','brand_id',];
  return NUMBER_FIELDS.includes(field);
};

const handleSubmit = async () => {
  // 显式遍历输入组件值并同步到 formFields
  formFields.forEach((field, index) => {
    const inputElement = document.querySelector(`#input-${index}`) as HTMLInputElement;
    if (inputElement) {
      field.inputValue = isNumberField(field.selectedField!) 
        ? Number(inputElement.value) 
        : inputElement.value;
    }
  });
  
    // 转换为目标数据结构
    const formData = formFields.reduce((acc, field) => {
    if (field.selectedField && field.inputValue !== undefined) {
      // 数字字段类型转换
      acc[field.selectedField] = isNumberField(field.selectedField) 
        ? Number(field.inputValue) 
        : field.inputValue;
    }
    return acc;
  }, {} as Record<keyof MinishopSpu, any>);
    //ids加入到最终提交数据
  const submitData = {
    ...formData,          // 保留原有字段
     ids: JSON.stringify(props.ids) // 新增序列化后的 ids 字段
  };

  await useAxiosRepo(uctoo_minishop_spu).api().edituctooMinishopSpu(JSON.parse(JSON.stringify(submitData)));
  message.success($t('page.EditSuccess'));
  emit('success'); 
};

onMounted(() => {
});
</script>

<template>
  <a-modal
    :open="visible"
    :title="mode === 'add' ? $t('page.Add') : $t('page.Edit')"
    @cancel="handleCancel"
    @ok="handleOk"
  >
  <template #footer>
        <a-button type="primary" @click="showDrawer">{{$t('page.Setting')}}</a-button>
        <a-button key="back" @click="handleCancel">{{$t('page.Cancel')}}</a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleOk">{{$t('page.Submit')}}</a-button>
      </template> <!-- -->
  <a-drawer :width="500" title="" :placement="placement" :open="open" @close="onClose">
    <template #extra>
      <a-button style="margin-right: 8px" @click="onClose">{{$t('page.Cancel')}}</a-button>
      <a-button type="primary" @click="onSetting">{{$t('page.Submit')}}</a-button>
    </template>
    <a-checkbox-group v-model:value="selectedFormItems" @change="handleFormItemChange">
      <a-checkbox v-for="(value, key) in formState" :key="key" :value="key" >
        {{ $t(`database_column.uctoo_minishop_spu.${key}`) }}
      </a-checkbox>
    </a-checkbox-group>
  </a-drawer>

  <a-form v-if="isIdsEmpty" ref="formRef" :model="formState" :rules="rules">
    <a-form-item v-if="selectedFormItems.includes('out_product_id')" :label="$t('database_column.uctoo.minishop_spu.out_product_id')" name="out_product_id">
          <a-input v-model:value="formState.out_product_id" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('title')" :label="$t('database_column.uctoo.minishop_spu.title')" name="title">
          <a-input v-model:value="formState.title" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('subtitle')" :label="$t('database_column.uctoo.minishop_spu.subtitle')" name="subtitle">
          <a-input v-model:value="formState.subtitle" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('headimg')" :label="$t('database_column.uctoo.minishop_spu.headimg')" name="headimg">
            <ImageUpload v-model="formState.headimg" :max-count="20" :upload-text="$t('page.image_upload')" />
          </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('status')" :label="$t('database_column.uctoo.minishop_spu.status')" name="status">
          <a-input v-model:value="formState.status" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('edit_status')" :label="$t('database_column.uctoo.minishop_spu.edit_status')" name="edit_status">
          <a-input v-model:value="formState.edit_status" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('min_price')" :label="$t('database_column.uctoo.minishop_spu.min_price')" name="min_price">
          <a-input v-model:value="formState.min_price" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('cats')" :label="$t('database_column.uctoo.minishop_spu.cats')" name="cats">
          <a-input v-model:value="formState.cats" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('attrs')" :label="$t('database_column.uctoo.minishop_spu.attrs')" name="attrs">
          <a-input v-model:value="formState.attrs" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('model')" :label="$t('database_column.uctoo.minishop_spu.model')" name="model">
          <a-input v-model:value="formState.model" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('dispatch_type')" :label="$t('database_column.uctoo.minishop_spu.dispatch_type')" name="dispatch_type">
          <a-input v-model:value="formState.dispatch_type" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('express_info')" :label="$t('database_column.uctoo.minishop_spu.express_info')" name="express_info">
          <a-input v-model:value="formState.express_info" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('shopcat')" :label="$t('database_column.uctoo.minishop_spu.shopcat')" name="shopcat">
          <a-input v-model:value="formState.shopcat" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('skus')" :label="$t('database_column.uctoo.minishop_spu.skus')" name="skus">
          <a-input v-model:value="formState.skus" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('sales_count')" :label="$t('database_column.uctoo.minishop_spu.sales_count')" name="sales_count">
          <a-input v-model:value="formState.sales_count" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('weigh')" :label="$t('database_column.uctoo.minishop_spu.weigh')" name="weigh">
          <a-input v-model:value="formState.weigh" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('template_id')" :label="$t('database_column.uctoo.minishop_spu.template_id')" name="template_id">
          <a-input v-model:value="formState.template_id" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('ext_json')" :label="$t('database_column.uctoo.minishop_spu.ext_json')" name="ext_json">
          <a-input v-model:value="formState.ext_json" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('memo')" :label="$t('database_column.uctoo.minishop_spu.memo')" name="memo">
          <a-input v-model:value="formState.memo" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('ext_attrs')" :label="$t('database_column.uctoo.minishop_spu.ext_attrs')" name="ext_attrs">
          <a-input v-model:value="formState.ext_attrs" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('start_at')" :label="$t('database_column.uctoo.minishop_spu.start_at')" name="start_at">
          <a-input v-model:value="formState.start_at" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('end_at')" :label="$t('database_column.uctoo.minishop_spu.end_at')" name="end_at">
          <a-input v-model:value="formState.end_at" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('meet_at')" :label="$t('database_column.uctoo.minishop_spu.meet_at')" name="meet_at">
          <a-input v-model:value="formState.meet_at" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('address')" :label="$t('database_column.uctoo.minishop_spu.address')" name="address">
          <a-input v-model:value="formState.address" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('latitude')" :label="$t('database_column.uctoo.minishop_spu.latitude')" name="latitude">
          <a-input v-model:value="formState.latitude" />
        </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('longitude')" :label="$t('database_column.uctoo.minishop_spu.longitude')" name="longitude">
          <a-input v-model:value="formState.longitude" />
        </a-form-item>

    <a-form-item v-if="selectedFormItems.includes('desc_info')" :label="$t('database_column.uctoo.minishop_spu.desc_info')" name="desc_info">
        <a-input v-model:value="formState.desc_info" />
        <ImageUpload
          v-model="formState.desc_info"
          :max-count="20"
          :upload-text="$t('page.image_upload')"
        />
      </a-form-item>
    <a-form-item v-if="selectedFormItems.includes('brand_id')" :label="$t('database_column.uctoo.minishop_spu.brand_id')" name="brand_id">
          <a-input v-model:value="formState.brand_id" />
        </a-form-item>
</a-form>

<!-- edit multi row -->
  <a-form v-else class="dynamic-form" ref="formRef" :model="formState">
    <a-form-item v-for="(field, index) in formFields" :key="index" class="form-row">
      <!-- 字段选择器 -->
      <a-space>
      <a-select 
        v-model="field.selectedField"
        :placeholder="$t('page.SelectField')"
        @change="(value:any) => handleFieldChange(index, value)"
        style="width: 160px"
      >
        <a-option 
          v-for="opt in getFieldOptions()" 
          :key="opt" 
          :value="opt"
        >
          {{ opt }}
        </a-option>
      </a-select>

      <!-- 动态输入组件：直接绑定到 field -->
      <a-input
        :id="`input-${index}`"
        v-if="field.selectedField && isNumberField(field.selectedField)"
        v-model.number="field.inputValue"
        type="number"
      />
      <a-input
        :id="`input-${index}`"
        v-else
        v-model="field.inputValue"
      />
      <a-button 
        v-if="index > 0" 
        @click="removeField(index)"
        type="danger"
      >
      <template #icon><VbenIcon icon="ant-design:minus-circle-outlined" /></template>
      </a-button>
      </a-space>
    </a-form-item>
  
    <a-button @click="addField" type="danger">
      <template #icon><VbenIcon icon="ant-design:plus-circle-outlined" /></template>
    </a-button>
  </a-form>
  </a-modal>
</template>
